<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px" style="text-align: left; margin-left: 0px;">
      <el-form-item label="昵称" prop="nickName">
        <el-input
            v-model="queryParams.nickName"
            placeholder="请输入昵称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="userName">
        <el-input
            v-model="queryParams.userName"
            placeholder="请输入姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="ownerList" >
      <el-table-column label="序号" align="center" prop="ownerId" />
      <el-table-column label="昵称" align="center" prop="nickName" :show-overflow-tooltip="true" />
      <el-table-column label="房间号" align="center" prop="roomNo" :show-overflow-tooltip="true" />
      <el-table-column label="姓名" align="center" prop="userName" />
      <el-table-column label="手机号" align="center" prop="phonenumber" width="120" />
      <el-table-column label="类型" align="center" prop="type">
        <template #default="scope">
          <el-tag type="success">{{ scope.row.type || '业主' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="绑定日期" align="center" prop="bindDate" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.bindDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="账号状态" align="center" prop="status" width="90">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['owner:owner:query']">查看</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['owner:owner:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改业主信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="ownerRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="房屋ID" prop="houseId">
          <el-input v-model="form.houseId" placeholder="请输入房屋ID" />
        </el-form-item>
        <!-- 可以根据需要添加更多字段 -->
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="房间号" prop="roomNo">
          <el-input v-model="form.roomNo" placeholder="请输入房间号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Owner">
import { listOwner, getOwner, delOwner, addOwner, updateOwner } from "@/api/owner/owner"
import router from "@/router/index.js";

const { proxy } = getCurrentInstance()
const { sys_normal_disable } = proxy.useDict('sys_normal_disable')


const ownerList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

//查看跳转具体信息页面
const handleView = (row) => {
  const ownerId = row.ownerId
  // 使用 router 而不是 proxy.$router
  // 使用 nextTick 确保 DOM 更新完成后再跳转
  proxy.$router.push(`/owner/owner/ownerMessage?id=${ownerId}`)
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    nickName: null,
    userName: null,
    roomNo: null,
    phonenumber: null,
    status: null
  },
  rules: {
    userId: [
      { required: true, message: "用户ID不能为空", trigger: "blur" }
    ],
    houseId: [
      { required: true, message: "房屋ID不能为空", trigger: "blur" }
    ],
    phonenumber: [
      { required: true, message: "手机号码不能为空", trigger: "blur" },
      {pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur"}
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询业主信息列表 */
function getList() {
  loading.value = true
  listOwner(queryParams.value).then(response => {
    ownerList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    ownerId: null,
    userId: null,
    houseId: null,
    nickName: null,
    userName: null,
    phonenumber: null,
    roomNo: null,
    status: "0"
  }
  proxy.resetForm("ownerRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.ownerId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加业主信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _ownerId = row.ownerId || ids.value
  getOwner(_ownerId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改业主信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["ownerRef"].validate(valid => {
    if (valid) {
      if (form.value.ownerId != null) {
        updateOwner(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addOwner(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ownerIds = row.ownerId || ids.value
  proxy.$modal.confirm('是否确认删除业主信息编号为"' + _ownerIds + '"的数据项？').then(function() {
    return delOwner(_ownerIds)
  }).then((response) => {
    getList()
    proxy.$modal.msgSuccess(response.msg)
  }).catch((error) => {    // 添加 error 参数
    console.log('删除错误:', error)
    proxy.$modal.msgError(error.response?.data?.msg || "删除失败")
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('owner/owner/export', {
    ...queryParams.value
  }, `owner_${new Date().getTime()}.xlsx`)
}

getList()
</script>

